<template>
	<view class="photos-page">
		<view class="tips-banner">
			<text class="tips-text">上传照片和视频</text>
			<text class="tips-subtext">照片最多9张，视频最多1个，照片越多越容易获得关注</text>
		</view>
		
		<view class="section">
			<view class="section-title">照片墙</view>
			<view class="photo-grid">
				<!-- 已上传照片 -->
				<view class="photo-item" v-for="(photo, index) in photos" :key="photo.id">
					<image class="photo-image" :src="photo.url" mode="aspectFill" @click="previewPhoto(index)"></image>
					<view class="delete-icon" @click.stop="deletePhoto(photo.id)">
						<text class="delete-text">×</text>
					</view>
				</view>
				
				<!-- 添加照片按钮 -->
				<view class="photo-item add-item" v-if="photos.length < 9" @click="uploadPhoto">
					<image class="add-icon" src="/static/images/add.png" mode="aspectFit"></image>
					<text class="add-text">添加照片</text>
				</view>
			</view>
		</view>
		
		<view class="section">
			<view class="section-title">视频展示</view>
			<view class="video-grid">
				<!-- 已上传视频 -->
				<view class="video-item" v-for="video in videos" :key="video.id">
					<video class="video-player" :src="video.play_url" :poster="video.cover_url" controls></video>
					<view class="delete-icon" @click="deleteVideo(video.id)">
						<text class="delete-text">×</text>
					</view>
				</view>
				
				<!-- 添加视频按钮 -->
				<view class="video-item add-item" v-if="videos.length === 0" @click="uploadVideo">
					<image class="add-icon" src="/static/images/add-video.png" mode="aspectFit"></image>
					<text class="add-text">添加视频</text>
				</view>
			</view>
		</view>
		
		<view class="submit-btn" @click="goBack">
			<text>完成</text>
		</view>
	</view>
</template>

<script>
	import { getUserPhotosApi, uploadPhotoApi, deletePhotoApi, getUserVideosApi, uploadVideoApi, deleteVideoApi, setPhotoAsAvatarApi } from '@/api/index.js';
	import { mapState, mapMutations } from 'vuex';
	
	export default {
		data() {
			return {
				photos: [],
				videos: []
			}
		},
		computed: {
			...mapState(['userInfo'])
		},
		onLoad() {
			this.getUserPhotos();
			this.getUserVideos();
		},
		methods: {
			...mapMutations(['setUserInfo']),
			
			// 获取用户照片
			getUserPhotos() {
				if (!this.userInfo || !this.userInfo.id) {
					this.$hr.methods.toast('请先登录');
					setTimeout(() => {
						this.$hr.methods.goPage('/login/index');
					}, 1500);
					return;
				}
				
				this.$hr.methods.loading();
				getUserPhotosApi().then(res => {
					this.$hr.methods.hideloading();
					if (res && Array.isArray(res)) {
						// 按照排序字段排序
						this.photos = res.sort((a, b) => a.sort - b.sort);
					}
				}).catch(() => {
					this.$hr.methods.hideloading();
					this.$hr.methods.toast('获取照片失败');
				});
			},
			
			// 获取用户视频
			getUserVideos() {
				getUserVideosApi().then(res => {
					if (res && Array.isArray(res)) {
						this.videos = res;
					}
				}).catch(err => {
					console.error('获取视频失败', err);
				});
			},
			
			// 上传照片
			uploadPhoto() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						
						// 上传照片
						this.$hr.methods.loading('上传中...');
						
						// 构建表单数据
						const formData = {
							sort: this.photos.length + 1,
							type: 'photo'
						};
						
						uni.uploadFile({
							url: this.$hr.config.SERVER_URL + '/api/users/v1/photos',
							filePath: tempFilePath,
							name: 'file',
							formData: formData,
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('token')
							},
							success: (uploadRes) => {
								this.$hr.methods.hideloading();
								const data = JSON.parse(uploadRes.data);
								if (data.code === 200) {
									this.$hr.methods.toast('上传成功', 'success');
									// 刷新照片列表
									this.getUserPhotos();
									
									// 如果是第一张照片，设为头像
									if (this.photos.length === 0) {
										this.setAsAvatar(data.data.photo_id);
									}
								} else {
									this.$hr.methods.toast(data.message || '上传失败');
								}
							},
							fail: () => {
								this.$hr.methods.hideloading();
								this.$hr.methods.toast('上传失败');
							}
						});
					}
				});
			},
			
			// 设置为头像
			setAsAvatar(photoId) {
				setPhotoAsAvatarApi(photoId).then(res => {
					if (res && res.avatar) {
						// 更新本地用户信息
						const updatedUserInfo = { ...this.userInfo, avatar: res.avatar };
						this.setUserInfo(updatedUserInfo);
					}
				}).catch(err => {
					console.error('设置头像失败', err);
				});
			},
			
			// 预览照片
			previewPhoto(index) {
				const urls = this.photos.map(photo => photo.url);
				uni.previewImage({
					urls: urls,
					current: index
				});
			},
			
			// 上传视频
			uploadVideo() {
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60,
					camera: 'back',
					success: (res) => {
						const tempFilePath = res.tempFilePath;
						const tempThumbPath = res.thumbTempFilePath;
						
						// 上传视频
						this.$hr.methods.loading('上传中...');
						
						uni.uploadFile({
							url: this.$hr.config.SERVER_URL + '/api/users/v1/videos',
							filePath: tempFilePath,
							name: 'file',
							formData: {
								type: 'video'
							},
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('token')
							},
							success: (uploadRes) => {
								this.$hr.methods.hideloading();
								const data = JSON.parse(uploadRes.data);
								if (data.code === 200) {
									this.$hr.methods.toast('上传成功', 'success');
									// 刷新视频列表
									this.getUserVideos();
								} else {
									this.$hr.methods.toast(data.message || '上传失败');
								}
							},
							fail: () => {
								this.$hr.methods.hideloading();
								this.$hr.methods.toast('上传失败');
							}
						});
					}
				});
			},
			
			// 删除照片
			deletePhoto(photoId) {
				this.$hr.methods.model({
					title: '提示',
					content: '确定要删除这张照片吗？',
					success: () => {
						this.$hr.methods.loading('删除中...');
						deletePhotoApi(photoId).then(() => {
							this.$hr.methods.hideloading();
							this.$hr.methods.toast('删除成功', 'success');
							// 刷新照片列表
							this.getUserPhotos();
						}).catch(() => {
							this.$hr.methods.hideloading();
							this.$hr.methods.toast('删除失败');
						});
					}
				});
			},
			
			// 删除视频
			deleteVideo(videoId) {
				this.$hr.methods.model({
					title: '提示',
					content: '确定要删除这个视频吗？',
					success: () => {
						this.$hr.methods.loading('删除中...');
						deleteVideoApi(videoId).then(() => {
							this.$hr.methods.hideloading();
							this.$hr.methods.toast('删除成功', 'success');
							// 刷新视频列表
							this.getUserVideos();
						}).catch(() => {
							this.$hr.methods.hideloading();
							this.$hr.methods.toast('删除失败');
						});
					}
				});
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style> 